package com.lantosec.hmrp.generator;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.ConstVal;
import com.baomidou.mybatisplus.generator.config.FileOutConfig;
import com.baomidou.mybatisplus.generator.config.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.FileType;
import com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.io.File;
import java.util.List;
import java.util.Map;

public class SuperFreemarkerTemplateEngine extends FreemarkerTemplateEngine {
    @Override
    public AbstractTemplateEngine batchOutput() {
        super.batchOutput();
        try {
            List<TableInfo> tableInfoList = getConfigBuilder().getTableInfoList();
            for (TableInfo tableInfo : tableInfoList) {
                Map<String, Object> objectMap = getObjectMap(tableInfo);
                String[] temp = getConfigBuilder().getPathInfo().get(ConstVal.ENTITY_PATH).split("\\\\");
                temp[temp.length - 1] = "vo";
                String path = String.join("\\", temp);
                TemplateConfig template = getConfigBuilder().getTemplate();
                // 自定义内容
                InjectionConfig injectionConfig = getConfigBuilder().getInjectionConfig();
                if (null != injectionConfig) {
                    injectionConfig.initTableMap(tableInfo);
                    objectMap.put("cfg", injectionConfig.getMap());
                    List<FileOutConfig> focList = injectionConfig.getFileOutConfigList();
                    if (CollectionUtils.isNotEmpty(focList)) {
                        for (FileOutConfig foc : focList) {
                            if (isCreate(FileType.OTHER, foc.outputFile(tableInfo))) {
                                writer(objectMap, foc.getTemplatePath(), foc.outputFile(tableInfo));
                            }
                        }
                    }
                }
                // vo.java
                String voName = tableInfo.getEntityName() + "VO";
                if (null != voName && null != path) {
                    String voFile = String.format((path + File.separator + "%s" + suffixJavaOrKt()), voName);
                    if (isCreate(FileType.ENTITY, voFile)) {
                        temp = template.getEntity(getConfigBuilder().getGlobalConfig().isKotlin()).split("/");
                        temp[temp.length - 1] = "vo.java";
                        String templatePath = String.join("\\", temp);
                        writer(objectMap, templateFilePath(templatePath), voFile);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("无法创建文件，请检查配置信息！", e);
        }
        return this;
    }
}
